/**
 * 文件名称: UnifiedComboQuery.js
 * 完整存储路径: frontend/static/js/UnifiedComboQuery.js
 *
 * 功能说明:
 *   统一查询组件，支持数据查询模式和报表模式
 *   主要功能包括：
 *     1. 动态添加查询条件行，支持多种控件：
 *          - "text": 文本输入框
 *          - "number_range": 数值区间查询（生成最小值和最大值两个输入框）
 *          - "dropdown"/"multi-select": 生成复选框组，每个选项前添加复选框
 *          - "checkbox": 生成单个复选框
 *     2. 配置驱动：通过配置参数控制不同模式的功能
 *     3. 角色化查询：报表模式支持角色选择（统计指标/分组/筛选）
 *     4. 模板查询：报表模式支持预设模板和自定义查询
 *     5. 列配置：数据查询模式支持列显示/隐藏配置
 *
 * 使用说明:
 *   在页面中，必须包含：
 *     - 条件容器 (id="advancedQueryContainer") 用于插入查询条件行
 *     - 隐藏输入框 (id="comboConditions") 用于存储查询条件 JSON 字符串
 *     - 操作按钮，根据模式不同有不同的按钮组合
 *
 * 配置参数:
 *   - mode: 'data_query' | 'report' - 查询模式
 *   - enableRoles: boolean - 是否启用角色选择（仅报表模式）
 *   - enableTemplates: boolean - 是否启用模板查询（仅报表模式）
 *   - enableColumnConfig: boolean - 是否启用列配置（仅数据查询模式）
 */

/**
 * 统一查询组件类
 */
class UnifiedComboQuery {
  constructor(config = {}) {
    this.config = {
      mode: config.mode || 'data_query', // 'data_query' | 'report'
      enableRoles: config.enableRoles !== undefined ? config.enableRoles : (config.mode === 'report'),
      enableTemplates: config.enableTemplates !== undefined ? config.enableTemplates : (config.mode === 'report'),
      enableColumnConfig: config.enableColumnConfig !== undefined ? config.enableColumnConfig : (config.mode === 'data_query'),
      containerId: config.containerId || 'advancedQueryContainer',
      conditionsId: config.conditionsId || 'comboConditions',
      ...config
    };
    
    // 配置驱动：从后端动态加载的配置
    this.fieldConfig = {};
    this.roleOptions = [];
    this.templates = {};
    this.componentConfig = {};
    
    console.log('🔧 统一查询组件初始化:', this.config);
  }
  
  /**
   * 初始化组件
   */
  async init() {
    console.log('🚀 初始化统一查询组件...');
    
    try {
      // 从后端加载配置
      await this.loadConfigurations();
      
      // 绑定按钮事件
      this.bindEvents();
      
      // 初始化列配置（如果启用）
      if (this.config.enableColumnConfig) {
        this.initColumnConfig();
      }
      
      console.log('✅ 统一查询组件初始化完成');
    } catch (error) {
      console.error('❌ 统一查询组件初始化失败:', error);
      throw error;
    }
  }
  
  /**
   * 从后端加载所有配置
   */
  async loadConfigurations() {
    console.log('📥 从后端加载配置...');
    
    try {
      // 加载完整配置
      const response = await fetch('/api/config/combo_query/complete_config');
      const result = await response.json();
      
      if (result.success) {
        this.fieldConfig = result.config.field_config || {};
        this.roleOptions = result.config.role_options || [];
        this.templates = result.config.templates || {};
        this.componentConfig = result.config.component_config || {};
        
        console.log('✅ 配置加载成功:', {
          fieldCount: Object.keys(this.fieldConfig).length,
          roleCount: this.roleOptions.length,
          templateCount: Object.keys(this.templates).length
        });
      } else {
        throw new Error(result.error || '配置加载失败');
      }
    } catch (error) {
      console.error('❌ 配置加载失败:', error);
      throw new Error(`配置加载失败: ${error.message}`);
    }
  }
  
  /**
   * 获取字段配置
   */
  getFieldConfig(fieldName) {
    return this.fieldConfig[fieldName] || null;
  }
  
  /**
   * 获取字段选项
   */
  getFieldOptions(fieldName) {
    const fieldConfig = this.getFieldConfig(fieldName);
    if (fieldConfig && fieldConfig.options) {
      return fieldConfig.options;
    }
    return [];
  }
  
  /**
   * 获取字段标签
   */
  getFieldLabel(fieldName) {
    const fieldConfig = this.getFieldConfig(fieldName);
    return fieldConfig ? fieldConfig.label : fieldName;
  }
  
  /**
   * 获取字段类型
   */
  getFieldType(fieldName) {
    const fieldConfig = this.getFieldConfig(fieldName);
    return fieldConfig ? fieldConfig.type : 'text';
  }
  
  /**
   * 绑定事件
   */
  bindEvents() {
    // 添加条件按钮
    const addBtn = document.getElementById('addConditionBtn');
    if (addBtn) {
      addBtn.addEventListener('click', () => this.addConditionRow());
    }
    
    // 清除条件按钮
    const clearBtn = document.getElementById('clearConditionsBtn');
    if (clearBtn) {
      clearBtn.addEventListener('click', () => this.clearConditions());
    }
    
    // 查询按钮
    const searchBtn = document.getElementById('searchBtn');
    if (searchBtn) {
      searchBtn.addEventListener('click', () => this.performSearch());
    }
    
    // 报表查询按钮
    const reportSearchBtn = document.getElementById('reportSearchBtn');
    if (reportSearchBtn) {
      reportSearchBtn.addEventListener('click', () => this.performReportSearch());
    }
  }
  
  /**
   * 添加查询条件行
   */
  addConditionRow() {
    const container = document.getElementById(this.config.containerId);
    if (!container) {
      console.error('❌ 找不到条件容器:', this.config.containerId);
      return;
    }
    
    const conditionRow = document.createElement('div');
    conditionRow.className = 'condition-row row g-1 mb-1';
    
    // 角色选择下拉框（如果启用）
    const roleDiv = document.createElement('div');
    roleDiv.className = 'col-md-2';
    const roleSelect = document.createElement('select');
    roleSelect.className = 'form-select form-select-sm condition-role';
    const defaultRoleOption = document.createElement('option');
    defaultRoleOption.value = '';
    defaultRoleOption.textContent = '选择角色';
    roleSelect.appendChild(defaultRoleOption);
    
    if (this.config.enableRoles) {
      for (const role of this.roleOptions) {
        const option = document.createElement('option');
        option.value = role.value;
        option.textContent = role.label;
        roleSelect.appendChild(option);
      }
    }
    roleDiv.appendChild(roleSelect);
    
    // 字段下拉框
    const fieldDiv = document.createElement('div');
    fieldDiv.className = 'col-md-3';
    const fieldSelect = document.createElement('select');
    fieldSelect.className = 'form-select form-select-sm condition-field';
    const defaultFieldOption = document.createElement('option');
    defaultFieldOption.value = '';
    defaultFieldOption.textContent = '选择字段';
    fieldSelect.appendChild(defaultFieldOption);
    
    for (const [fieldName, fieldConfig] of Object.entries(this.fieldConfig)) {
      const option = document.createElement('option');
      option.value = fieldName;
      option.textContent = fieldConfig.label;
      fieldSelect.appendChild(option);
    }
    fieldDiv.appendChild(fieldSelect);
    
    // 运算符下拉框
    const operatorDiv = document.createElement('div');
    operatorDiv.className = 'col-md-2';
    const operatorSelect = document.createElement('select');
    operatorSelect.className = 'form-select form-select-sm condition-operator';
    const operators = [
      { value: 'like', label: 'like' },
      { value: '=', label: '=' },
      { value: '!=', label: '!=' },
      { value: '>', label: '>' },
      { value: '<', label: '<' },
      { value: '>=', label: '>=' },
      { value: '<=', label: '<=' }
    ];
    operators.forEach((op) => {
      const opOption = document.createElement('option');
      opOption.value = op.value;
      opOption.textContent = op.label;
      operatorSelect.appendChild(opOption);
    });
    operatorDiv.appendChild(operatorSelect);
    
    // 值输入区域
    const valueDiv = document.createElement('div');
    valueDiv.className = 'col-md-3';
    let valueInput = document.createElement('input');
    valueInput.type = 'text';
    valueInput.className = 'form-control form-control-sm condition-value';
    valueInput.placeholder = '输入查询值';
    valueDiv.appendChild(valueInput);
    
    // 删除按钮
    const deleteDiv = document.createElement('div');
    deleteDiv.className = 'col-md-2';
    const deleteBtn = document.createElement('button');
    deleteBtn.type = 'button';
    deleteBtn.className = 'btn btn-danger btn-sm condition-delete';
    deleteBtn.textContent = '×';
    deleteBtn.addEventListener('click', function () {
      conditionRow.remove();
    });
    deleteDiv.appendChild(deleteBtn);
    
    // 拼接条件行
    conditionRow.appendChild(roleDiv);
    conditionRow.appendChild(fieldDiv);
    conditionRow.appendChild(operatorDiv);
    conditionRow.appendChild(valueDiv);
    conditionRow.appendChild(deleteDiv);
    
    // 根据所选字段更新值输入区域
    fieldSelect.addEventListener('change', function () {
      const selectedField = fieldSelect.value;
      valueDiv.innerHTML = '';
      
      // 强制干预方式分组的操作符为 "in"
      if (selectedField === 'intervention_type') {
        operatorSelect.value = 'in';
        operatorSelect.disabled = true; // 禁止修改操作符
      } else {
        operatorSelect.disabled = false;
      }
      
      if (!selectedField) {
        valueInput = document.createElement('input');
        valueInput.type = 'text';
        valueInput.className = 'form-control form-control-sm condition-value';
        valueInput.placeholder = '输入查询值';
        valueDiv.appendChild(valueInput);
        return;
      }
      
      const fieldConfig = this.comboQuery.getFieldConfig(selectedField);
      if (!fieldConfig) {
        valueInput = document.createElement('input');
        valueInput.type = 'text';
        valueInput.className = 'form-control form-control-sm condition-value';
        valueInput.placeholder = '输入查询值';
        valueDiv.appendChild(valueInput);
        return;
      }
      
      switch (fieldConfig.type) {
        case 'text':
          valueInput = document.createElement('input');
          valueInput.type = 'text';
          valueInput.className = 'form-control form-control-sm condition-value';
          valueInput.placeholder = '输入查询值';
          valueDiv.appendChild(valueInput);
          break;
        case 'number_range':
          const minInput = document.createElement('input');
          minInput.type = 'number';
          minInput.className = 'form-control form-control-sm condition-value-min';
          minInput.placeholder = '最小值';
          const maxInput = document.createElement('input');
          maxInput.type = 'number';
          maxInput.className = 'form-control form-control-sm condition-value-max';
          maxInput.placeholder = '最大值';
          const rangeDiv = document.createElement('div');
          rangeDiv.className = 'd-flex gap-1';
          rangeDiv.appendChild(minInput);
          rangeDiv.appendChild(maxInput);
          valueDiv.appendChild(rangeDiv);
          break;
        case 'dropdown':
        case 'multi-select':
          const multiDiv = document.createElement('div');
          multiDiv.className = 'd-flex flex-wrap gap-1';
          const options = fieldConfig.options || [];
          options.forEach((opt) => {
            const label = document.createElement('label');
            label.className = 'form-check form-check-inline';
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.className = 'form-check-input condition-value-multi';
            checkbox.value = opt;
            label.appendChild(checkbox);
            const span = document.createElement('span');
            span.className = 'form-check-label';
            span.textContent = opt;
            label.appendChild(span);
            multiDiv.appendChild(label);
          });
          valueDiv.appendChild(multiDiv);
          break;
        case 'checkbox':
          const singleCheckboxDiv = document.createElement('div');
          singleCheckboxDiv.className = 'form-check';
          const singleCheckbox = document.createElement('input');
          singleCheckbox.type = 'checkbox';
          singleCheckbox.className = 'form-check-input condition-value-checkbox';
          singleCheckboxDiv.appendChild(singleCheckbox);
          const checkboxLabel = document.createElement('label');
          checkboxLabel.className = 'form-check-label';
          checkboxLabel.textContent = '选中';
          singleCheckboxDiv.appendChild(checkboxLabel);
          valueDiv.appendChild(singleCheckboxDiv);
          break;
        default:
          valueInput = document.createElement('input');
          valueInput.type = 'text';
          valueInput.className = 'form-control form-control-sm condition-value';
          valueInput.placeholder = '输入查询值';
          valueDiv.appendChild(valueInput);
          break;
      }
    }.bind(this)); // 绑定this上下文
    
    container.appendChild(conditionRow);
  }
  
  /**
   * 构建字段选择下拉框
   */
  buildFieldSelect() {
    let options = '<option value="">请选择字段</option>';
    
    for (const [fieldName, fieldConfig] of Object.entries(this.fieldConfig)) {
      options += `<option value="${fieldName}">${fieldConfig.label}</option>`;
    }
    
    return `<select name="field" class="form-select">
      ${options}
    </select>`;
  }
  
  /**
   * 构建角色选择下拉框
   */
  buildRoleSelect() {
    let options = '<option value="">角色</option>';
    
    for (const role of this.roleOptions) {
      options += `<option value="${role.value}">${role.label}</option>`;
    }
    
    return `<select name="role" class="form-select">
      ${options}
    </select>`;
  }
  
  /**
   * 构建操作符选择下拉框
   */
  buildOperatorSelect() {
    return `<select name="operator" class="form-select">
      <option value="=">=</option>
      <option value="!=">!=</option>
      <option value=">">></option>
      <option value="<"><</option>
      <option value=">=">>=</option>
      <option value="<="><=</option>
      <option value="like">包含</option>
      <option value="not like">不包含</option>
      <option value="in">在列表中</option>
      <option value="not in">不在列表中</option>
    </select>`;
  }
  
  /**
   * 更新值输入控件
   */
  updateValueInput(valueDiv, selectedField) {
    if (!selectedField) {
      valueDiv.innerHTML = '<input type="text" class="form-control" placeholder="请输入值">';
      return;
    }
    
    const fieldConfig = this.getFieldConfig(selectedField);
    if (!fieldConfig) {
      valueDiv.innerHTML = '<input type="text" class="form-control" placeholder="请输入值">';
      return;
    }
    
    const fieldType = fieldConfig.type;
    const options = fieldConfig.options || [];
    
    switch (fieldType) {
      case 'text':
        valueDiv.innerHTML = '<input type="text" class="form-control" placeholder="请输入值">';
        break;
        
      case 'number_range':
        valueDiv.innerHTML = `
          <div class="row">
            <div class="col-6">
              <input type="number" class="form-control" placeholder="最小值" step="0.01">
            </div>
            <div class="col-6">
              <input type="number" class="form-control" placeholder="最大值" step="0.01">
            </div>
          </div>
        `;
        break;
        
      case 'dropdown':
        let dropdownOptions = '<option value="">请选择</option>';
        for (const option of options) {
          dropdownOptions += `<option value="${option}">${option}</option>`;
        }
        valueDiv.innerHTML = `<select class="form-select">${dropdownOptions}</select>`;
        break;
        
      case 'multi-select':
        let checkboxGroup = '<div class="checkbox-group">';
        for (const option of options) {
          checkboxGroup += `
            <div class="form-check">
              <input class="form-check-input" type="checkbox" value="${option}" id="check_${option}">
              <label class="form-check-label" for="check_${option}">${option}</label>
            </div>
          `;
        }
        checkboxGroup += '</div>';
        valueDiv.innerHTML = checkboxGroup;
        break;
        
      case 'checkbox':
        valueDiv.innerHTML = `
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="check_${selectedField}">
            <label class="form-check-label" for="check_${selectedField}">是</label>
          </div>
        `;
        break;
        
      default:
        valueDiv.innerHTML = '<input type="text" class="form-control" placeholder="请输入值">';
    }
  }
  
  /**
   * 删除查询条件行
   */
  removeConditionRow(rowId) {
    const row = document.getElementById(rowId);
    if (row) {
      row.remove();
    }
  }
  
  /**
   * 获取组合查询条件
   */
  getComboConditions() {
    const conditions = [];
    const rows = document.querySelectorAll('.condition-row');
    
    for (const row of rows) {
      const roleEl = row.querySelector('.condition-role');
      const fieldEl = row.querySelector('.condition-field');
      const operatorEl = row.querySelector('.condition-operator');
      
      if (!fieldEl || !fieldEl.value) continue;
      
      const role = roleEl ? roleEl.value.trim() : '';
      const field = fieldEl.value.trim();
      let operator = operatorEl ? operatorEl.value.trim() : '';
      
      // 强制干预方式分组的操作符为 "in"
      if (field === 'intervention_type') {
        operator = 'in';
      }
      
      if (!field || !operator) continue;
      
      // 检查角色、字段、操作符是否有效
      if (!role || !field || !operator) {
        continue; // 跳过无效行
      }
      
      const value = this.extractValueFromRow(row, field);
      
      // 检查值是否有效
      if (value === null || value === '' || 
          (Array.isArray(value) && value.length === 0)) {
        continue; // 跳过无效行
      }
      
      // 打印调试日志
      console.log(`Field: ${field}, Operator: ${operator}, Value: ${value}`);
      
      // 返回格式与原始组件完全兼容
      conditions.push({
        role: role,
        field: field,
        operator: operator,
        value: value
      });
    }
    
    return conditions;
  }
  
  /**
   * 从行中提取值（使用原始组件的选择器）
   */
  extractValueFromRow(row, fieldName) {
    const fieldConfig = this.getFieldConfig(fieldName);
    const fieldType = fieldConfig ? fieldConfig.type : 'text';
    
    switch (fieldType) {
      case 'text':
        const textInput = row.querySelector('.condition-value');
        return textInput && textInput.value ? textInput.value.trim() : null;
        
      case 'number_range':
        const minEl = row.querySelector('.condition-value-min');
        const maxEl = row.querySelector('.condition-value-max');
        const min = minEl && minEl.value ? minEl.value.trim() : '';
        const max = maxEl && maxEl.value ? maxEl.value.trim() : '';
        return { min: min, max: max };
        
      case 'dropdown':
        const select = row.querySelector('.condition-value');
        return select && select.value ? select.value : null;
        
      case 'multi-select':
        const checkboxes = row.querySelectorAll('.condition-value-multi:checked');
        const values = [];
        checkboxes.forEach((cb) => {
          // 调试输出：打印每个复选框的状态
          console.log('Multi-select - value:', cb.value, 'checked:', cb.checked);
          if (cb.checked) {
            values.push(cb.value);
          }
        });
        return values;
        
      case 'checkbox':
        const checkbox = row.querySelector('.condition-value-checkbox');
        return checkbox ? checkbox.checked : false;
        
      default:
        const input = row.querySelector('.condition-value');
        return input && input.value ? input.value.trim() : null;
    }
  }
  
  /**
   * 清除所有条件
   */
  clearConditions() {
    const container = document.getElementById(this.config.containerId);
    if (container) {
      container.innerHTML = '';
    }
    
    const conditionsInput = document.getElementById(this.config.conditionsId);
    if (conditionsInput) {
      conditionsInput.value = '';
    }
  }
  
  /**
   * 执行查询
   */
  performSearch() {
    const conditions = this.getComboConditions();
    
    // 更新隐藏输入框
    const conditionsInput = document.getElementById(this.config.conditionsId);
    if (conditionsInput) {
      conditionsInput.value = JSON.stringify(conditions);
    }
    
    console.log('🔍 执行查询:', conditions);
    
    // 触发查询事件
    const event = new CustomEvent('comboQuerySearch', {
      detail: { conditions: conditions, mode: this.config.mode }
    });
    document.dispatchEvent(event);
  }
  
  /**
   * 执行报表查询
   */
  performReportSearch() {
    const conditions = this.getComboConditions();
    
    console.log('📊 执行报表查询:', conditions);
    
    // 触发报表查询事件
    const event = new CustomEvent('comboQueryReportSearch', {
      detail: { conditions: conditions }
    });
    document.dispatchEvent(event);
  }
  
  /**
   * 初始化列配置
   */
  initColumnConfig() {
    if (!this.config.enableColumnConfig) {
      console.log('📋 列配置功能未启用');
      return;
    }
    
    console.log('📋 初始化列配置功能...');
    
    // 创建列配置管理器
    this.columnConfig = new ColumnConfig(this);
    
    // 创建列配置UI
    this.createColumnConfigUI();
    
    // 加载默认列配置
    this.loadDefaultColumnConfig();
  }
  
  /**
   * 创建列配置UI
   */
  createColumnConfigUI() {
    // 查找或创建列配置容器
    let configContainer = document.getElementById('columnConfigContainer');
    if (!configContainer) {
      configContainer = document.createElement('div');
      configContainer.id = 'columnConfigContainer';
      configContainer.className = 'card mt-3';
      configContainer.innerHTML = `
        <div class="card-header">
          <h6 class="mb-0">
            <i class="fas fa-columns"></i> 列配置
          </h6>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6">
              <label class="form-label">选择要显示的列:</label>
              <div id="columnSelectionArea" class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                <!-- 列选择复选框将在这里动态生成 -->
              </div>
            </div>
            <div class="col-md-6">
              <label class="form-label">当前显示列:</label>
              <div id="currentColumnsDisplay" class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                <!-- 当前显示的列将在这里显示 -->
              </div>
            </div>
          </div>
          <div class="row mt-3">
            <div class="col-md-12">
              <button type="button" class="btn btn-primary btn-sm me-2" onclick="this.columnConfig?.applyColumnConfig()">
                <i class="fas fa-check"></i> 应用配置
              </button>
              <button type="button" class="btn btn-secondary btn-sm me-2" onclick="this.columnConfig?.resetToDefault()">
                <i class="fas fa-undo"></i> 重置默认
              </button>
              <button type="button" class="btn btn-info btn-sm" onclick="this.columnConfig?.exportColumnConfig()">
                <i class="fas fa-download"></i> 导出配置
              </button>
            </div>
          </div>
        </div>
      `;
      
      // 插入到查询区域后面
      const queryContainer = document.getElementById(this.config.containerId);
      if (queryContainer && queryContainer.parentNode) {
        queryContainer.parentNode.insertBefore(configContainer, queryContainer.nextSibling);
      }
    }
    
    // 绑定按钮事件
    const applyBtn = configContainer.querySelector('button[onclick*="applyColumnConfig"]');
    const resetBtn = configContainer.querySelector('button[onclick*="resetToDefault"]');
    const exportBtn = configContainer.querySelector('button[onclick*="exportColumnConfig"]');
    
    if (applyBtn) {
      applyBtn.onclick = () => this.columnConfig.applyColumnConfig();
    }
    if (resetBtn) {
      resetBtn.onclick = () => this.columnConfig.resetToDefault();
    }
    if (exportBtn) {
      exportBtn.onclick = () => this.columnConfig.exportColumnConfig();
    }
  }
  
  /**
   * 加载默认列配置
   */
  async loadDefaultColumnConfig() {
    try {
      // 从后端加载默认列配置
      const response = await fetch('/api/config/default-columns');
      const result = await response.json();
      
      if (result.success) {
        this.columnConfig.setDefaultColumns(result.columns || []);
        this.columnConfig.renderColumnSelection();
        this.columnConfig.updateCurrentColumnsDisplay();
      } else {
        console.warn('⚠️ 默认列配置加载失败，使用内置默认配置');
        this.columnConfig.setDefaultColumns(this.getDefaultColumns());
        this.columnConfig.renderColumnSelection();
        this.columnConfig.updateCurrentColumnsDisplay();
      }
    } catch (error) {
      console.error('❌ 默认列配置加载失败:', error);
      this.columnConfig.setDefaultColumns(this.getDefaultColumns());
      this.columnConfig.renderColumnSelection();
      this.columnConfig.updateCurrentColumnsDisplay();
    }
  }
  
  /**
   * 获取默认列配置
   */
  getDefaultColumns() {
    // 根据模式返回不同的默认列
    if (this.config.mode === 'data_query') {
      return [
        'education_id', 'name', 'school', 'grade', 'class_name', 
        'gender', 'age', 'parent_name', 'actions'
      ];
    } else {
      return [
        'education_id', 'name', 'school', 'grade', 'class_name', 
        'gender', 'age', 'vision_level', 'intervention_type'
      ];
    }
  }
}

/**
 * 列配置管理类
 */
class ColumnConfig {
  constructor(comboQuery) {
    this.comboQuery = comboQuery;
    this.availableColumns = [];
    this.selectedColumns = [];
    this.defaultColumns = [];
    this.columnDisplayNames = {};
  }
  
  /**
   * 设置可用列
   */
  setAvailableColumns(columns) {
    this.availableColumns = columns;
    this.updateColumnDisplayNames();
  }
  
  /**
   * 设置默认列
   */
  setDefaultColumns(columns) {
    this.defaultColumns = columns;
    this.selectedColumns = [...columns]; // 初始选中默认列
  }
  
  /**
   * 更新列显示名称映射
   */
  updateColumnDisplayNames() {
    this.columnDisplayNames = {};
    for (const column of this.availableColumns) {
      const fieldConfig = this.comboQuery.getFieldConfig(column);
      this.columnDisplayNames[column] = fieldConfig ? fieldConfig.label : column;
    }
  }
  
  /**
   * 渲染列选择界面
   */
  renderColumnSelection() {
    const selectionArea = document.getElementById('columnSelectionArea');
    if (!selectionArea) return;
    
    let html = '';
    
    // 如果没有可用列，从字段配置中获取
    if (this.availableColumns.length === 0) {
      this.availableColumns = Object.keys(this.comboQuery.fieldConfig);
      this.updateColumnDisplayNames();
    }
    
    for (const column of this.availableColumns) {
      const displayName = this.columnDisplayNames[column] || column;
      const isSelected = this.selectedColumns.includes(column);
      
      html += `
        <div class="form-check">
          <input class="form-check-input column-checkbox" type="checkbox" 
                 value="${column}" id="col_${column}" 
                 ${isSelected ? 'checked' : ''}>
          <label class="form-check-label" for="col_${column}">
            ${displayName}
          </label>
        </div>
      `;
    }
    
    selectionArea.innerHTML = html;
    
    // 绑定复选框事件
    const checkboxes = selectionArea.querySelectorAll('.column-checkbox');
    checkboxes.forEach(checkbox => {
      checkbox.addEventListener('change', () => {
        this.onColumnSelectionChange(checkbox.value, checkbox.checked);
      });
    });
  }
  
  /**
   * 列选择变化处理
   */
  onColumnSelectionChange(column, isSelected) {
    if (isSelected) {
      if (!this.selectedColumns.includes(column)) {
        this.selectedColumns.push(column);
      }
    } else {
      const index = this.selectedColumns.indexOf(column);
      if (index > -1) {
        this.selectedColumns.splice(index, 1);
      }
    }
    
    this.updateCurrentColumnsDisplay();
  }
  
  /**
   * 更新当前显示列
   */
  updateCurrentColumnsDisplay() {
    const displayArea = document.getElementById('currentColumnsDisplay');
    if (!displayArea) return;
    
    if (this.selectedColumns.length === 0) {
      displayArea.innerHTML = '<p class="text-muted">未选择任何列</p>';
      return;
    }
    
    let html = '<div class="d-flex flex-wrap gap-1">';
    for (const column of this.selectedColumns) {
      const displayName = this.columnDisplayNames[column] || column;
      html += `
        <span class="badge bg-primary">
          ${displayName}
          <button type="button" class="btn-close btn-close-white ms-1" 
                  style="font-size: 0.5em;" 
                  onclick="this.parentElement.remove(); this.columnConfig?.removeColumn('${column}')">
          </button>
        </span>
      `;
    }
    html += '</div>';
    
    displayArea.innerHTML = html;
  }
  
  /**
   * 移除列
   */
  removeColumn(column) {
    const index = this.selectedColumns.indexOf(column);
    if (index > -1) {
      this.selectedColumns.splice(index, 1);
      this.renderColumnSelection(); // 重新渲染以更新复选框状态
      this.updateCurrentColumnsDisplay();
    }
  }
  
  /**
   * 应用列配置
   */
  applyColumnConfig() {
    console.log('📋 应用列配置:', this.selectedColumns);
    
    // 触发列配置应用事件
    const event = new CustomEvent('columnConfigApplied', {
      detail: { 
        columns: this.selectedColumns,
        displayNames: this.columnDisplayNames
      }
    });
    document.dispatchEvent(event);
    
    // 显示成功消息
    this.showMessage('列配置已应用', 'success');
  }
  
  /**
   * 重置为默认配置
   */
  resetToDefault() {
    this.selectedColumns = [...this.defaultColumns];
    this.renderColumnSelection();
    this.updateCurrentColumnsDisplay();
    this.showMessage('已重置为默认配置', 'info');
  }
  
  /**
   * 导出列配置
   */
  exportColumnConfig() {
    const config = {
      columns: this.selectedColumns,
      displayNames: this.columnDisplayNames,
      timestamp: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `column_config_${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    this.showMessage('列配置已导出', 'success');
  }
  
  /**
   * 显示消息
   */
  showMessage(message, type = 'info') {
    // 创建临时消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    messageDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    messageDiv.innerHTML = `
      ${message}
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
      if (messageDiv.parentNode) {
        messageDiv.parentNode.removeChild(messageDiv);
      }
    }, 3000);
  }
  
  /**
   * 获取当前选中的列
   */
  getSelectedColumns() {
    return this.selectedColumns;
  }
  
  /**
   * 获取列显示名称
   */
  getColumnDisplayName(column) {
    return this.columnDisplayNames[column] || column;
  }
}

/**
 * 初始化统一查询组件的全局函数
 */
function initUnifiedComboQuery(config = {}) {
  const comboQuery = new UnifiedComboQuery(config);
  comboQuery.init().catch(error => {
    console.error('❌ 统一查询组件初始化失败:', error);
  });
  return comboQuery;
}

// 导出到全局
window.UnifiedComboQuery = UnifiedComboQuery;
window.initUnifiedComboQuery = initUnifiedComboQuery;
window.getComboConditions = function() {
  // 兼容性函数，用于向后兼容
  const container = document.getElementById('advancedQueryContainer');
  if (container) {
    const unifiedQuery = new UnifiedComboQuery();
    return unifiedQuery.getComboConditions();
  }
  return [];
};
window.clearConditions = function() {
  // 兼容性函数，用于向后兼容
  const container = document.getElementById('advancedQueryContainer');
  if (container) {
    const unifiedQuery = new UnifiedComboQuery();
    unifiedQuery.clearConditions();
  }
};

// DOMContentLoaded 后自动初始化（如果页面有相关元素）
document.addEventListener("DOMContentLoaded", function () {
  // 检查页面是否有查询容器，如果有则自动初始化
  const container = document.getElementById('advancedQueryContainer');
  if (container) {
    console.log("检测到查询容器，自动初始化统一查询组件...");
    
    // 根据页面特征判断模式
    let config = {
      mode: 'data_query' // 默认数据查询模式
    };
    
    // 如果页面有报表相关元素，则设置为报表模式
    if (document.getElementById('reportSearchBtn') || document.getElementById('templateSelect')) {
      config.mode = 'report';
    }
    
    initUnifiedComboQuery(config);
  }
}); 